
\section{Layers}

{
\tikzset{external/figure name/.add={}{layers_}}

It is important that several parts of an axis are drawn ``on top'' of others.
Usually, \PGFPlots{} ensures this by drawing them in a suitable sequence
(usually background followed by grid lines, followed by tick lines and tick
labels, followed by plots and finally axis descriptions). While this works
reasonable in most cases, there are cases where more control is desired. One
common use case is if multiple axes shall be drawn into the same picture: here,
the sequence from above should be applied to all involved axes simultaneously.


\subsection{Summary}

This section is the technical reference for using and customizing layered
graphics in \PGFPlots{}. As such, it is hard reading.

For most purposes, the following is \emph{completely} sufficient for you: If
you want to enable layered graphics, put the following statement into the
|tikzpicture| which is supposed to have layered graphics:

\begin{codeexample}[code only]
\begin{tikzpicture}
        \pgfplotsset{set layers}
    \begin{axis}
        ...
    \end{axis}

    % perhaps a second axis which should use the same layers?
    \begin{axis}
        ...
    \end{axis}
\end{tikzpicture}
\end{codeexample}
    %
\noindent This enables layered graphics for that specific |tikzpicture|.

You may want layered graphics if you have multiple axes in the same picture, of
if you have specific needs for your plot.

Consider reading |on layer| if you want to move particular elements of your
axis to a different layer.


\subsection{Using Predefined Layers}

The main key to control layered graphics with \PGFPlots{} is |set layers|:

\pgfkeys{
    /pgfmanual/gray key prefixes/.add={/pgfplots/layers/,}{},
}

\begin{pgfplotskey}{set layers=\mchoice{none,\normalfont\meta{layer configuration name}} (initially none)}
   This key enables layered graphics for either the current axis or for all
   following axes.

   Enabling layered graphics has the effect that the order in which graphical
   elements are given is unrelated to the ordering in which they will be drawn.
   The main benefit is if you have multiple axes in the same figure: the axes
   can share the same layers.

   The invocation |set layers=none| disables layered graphics.

   The invocation |set layers| (without equal sign and without arguments) is
   the same as if you would write |set layers=||default|.

   In all other cases, |set layers| expects a \meta{layer configuration name}.
   There are two predefined configurations available (the prefix
   |/pgfplots/layers/| is optional):

   \begin{pgfplotskey}{layers/standard}
       A layer configuration which defines the layers \texttt{axis background},
       \texttt{axis grid}, \texttt{axis ticks}, \texttt{axis lines},
       \texttt{axis tick labels}, \texttt{main}, \texttt{axis descriptions},
       \texttt{axis foreground}. They are drawn in the order of appearance.
   \end{pgfplotskey}

   \begin{pgfplotskey}{layers/axis on top}
       A layer configuration which uses the same layer names as
       |layers/standard|, but with a different sequence: \texttt{axis
       background}, \texttt{main}, \texttt{axis grid}, \texttt{axis ticks},
       \texttt{axis lines}, \texttt{axis tick labels}, \texttt{axis
       descriptions}, \texttt{axis foreground}.

        This layer is automatically used if the key |axis on top| is used
        together with |set layers=|\meta{any layer configuration name}.
   \end{pgfplotskey}

    As soon as the key |set layers=|\meta{layer configuration name} is
    encountered, \PGFPlots{} starts the \pgfname{} command
    |\pgfsetlayers|\marg{layer names} with the layer names of the respective
    configuration. Usually, this \emph{replaces} the current layer
    configuration of the embedding |tikzpicture|. Furthermore, |set layers|
    stores the name of \meta{layer configuration name} such that every
    following |axis| knows how to map graphical elements to layer names.

    There is one huge difference to any other key which tunes \PGFPlots{}:
    layer configurations are properties of a complete |tikzpicture| whereas any
    other option affects only axis objects and their contents. Layers, however,
    affect every graphical element of the embedding picture. Due to this
    property, layer configurations need to be given at one of several supported
    positions:
    %
    \begin{enumerate}
        \item\label{en:layers_directly} Directly within the picture:
            %
\begin{codeexample}[code only]
\begin{tikzpicture}
        \pgfplotsset{set layers=default}
    \begin{axis}
        ...
    \end{axis}
\end{tikzpicture}
\end{codeexample}
            %
            \noindent This option explicitly tells the reader of your source
            code that a significant portion of your picture has been changed:
            the complete picture has and uses a \meta{layer configuration name}
            (in this case |default|).
        \item As option for one or more axes which is/are directly within the
            picture:
            %
\begin{codeexample}[code only]
\begin{tikzpicture}
    \begin{axis}[set layers]
        ...
    \end{axis}
\end{tikzpicture}
\end{codeexample}
            %
            Here, \PGFPlots{} implicitly communicates its layer configuration
            to the enclosing |tikzpicture|. Thus, the effect of |set layers| is
            \emph{not local to an axis}; it survives until |\end{tikzpicture}|.
            Any other option only survives until |\end{axis}|.

            In this case, only the \emph{last} activated layer configuration
            will apply to the picture.

            \paragraph{Limitation: no environments or local \TeX{} groups allowed.}

            Standard usages as within the examples of this manual will always
            work. But since the layer name configuration is essentially part
            of a \PGF{} picture (at a low level), one cannot arbitrarily set
            them; \PGF{} will complain if they are changed within some nested
            \TeX{} groups or \LaTeX{} environments. Typically, you will never
            need to worry about this.

            In short, the following examples are \emph{forbidden} because the
            axis is within locally nested groups.
            %
\begin{codeexample}[code only]
\begin{tikzpicture}
    {% FORBIDDEN! Consider using case (1) above!
        \begin{axis}[set layers]
            ...
        \end{axis}
    }
\end{tikzpicture}
\end{codeexample}

\begin{codeexample}[code only]
\begin{tikzpicture}
    \begin{scope} % FORBIDDEN! Consider using case (1) above!
        \begin{axis}[set layers]
            ...
        \end{axis}
    \end{scope}
\end{tikzpicture}
\end{codeexample}
            %
            \noindent These examples are forbidden because the layer
            configuration will be cleared by the `|}|' of the first forbidden
            example and by the `|\end{scope}|' of the second example. A
            solution would be one of the different placement options (i.e.\@
            choice \ref{en:layers_directly} or \ref{en:layers_outside}).
        \item\label{en:layers_outside} outside of any picture:
            %
\begin{codeexample}[code only]
\pgfplotsset{set layers=default}
\begin{tikzpicture}
    \begin{axis}
        ...
    \end{axis}
\end{tikzpicture}
\end{codeexample}
            %
            \noindent This choice configures the layer configuration for
            \emph{every} following |tikzpicture|.
    \end{enumerate}


    \paragraph{Limitation: axis alignment restricted to inner anchors.}

    This applies only if you changed the default value of |anchor| (which is
    |anchor=south west|). Any axis which uses layered graphics should use one
    of the following values of |anchor|: |north|, |north west|, |west|,
    |south west|, |south|, |south east|, |east|, |north east|, |north|,
    |center|, |origin|, |above origin|, |left of origin|, |right of origin|,
    |below origin|. In case you really need another anchor, \PGFPlots{}
    requires the use of |cell picture=true|, causing the layers to be local for
    that specific axis.

    The technical background for this limitation is a hen-and-egg problem:
    outer anchors (like |outer south west|) are only available \emph{after} the
    complete axis has been generated -- and layers can only be drawn after each
    drawing instruction has been issued. The technical keys for further reading
    are |cell picture=false| or |cell picture=if necessary| (one of them is
    active for layered graphics).
\end{pgfplotskey}

\begin{command}{\pgfplotssetlayers}
    An alias for |\pgfplotsset{set layers}|. It activates the |layers/default|
    layer configuration.
\end{command}

\begin{command}{\pgfplotssetlayers\marg{layer configuration name}}
    An alias for |\pgfplotsset{set layers=|\marg{layer configuration name}|}|.
\end{command}

\begin{handler}{{.define layer set}=\marg{ordered layer names}\marg{style definitions}}
    Allows to define a new layer set configuration named \meta{key}.
    Afterwards, \meta{key} can be specified as argument to |set layers| as
    follows:
    %
    \begin{itemize}
        \item if \meta{key} has the type |/pgfplots/layers/|\meta{name}, you
            can write |set layers=|\meta{name}.

            Example: |/pgfplots/layers/my layers/.define layer set=|$\cdots$
            can be activated by means of the shorthand notation
            |set layers=my layers|.
        \item if \meta{key} is an arbitrary key path, |set layers| expects
            the fully qualified \meta{key} name.

            Example: |/user/my layers/.define layer set=|$\cdots$ can be
            activated by means of the full value
            |set layers=/user/my layers|.
    \end{itemize}

    The first argument \meta{ordered layer names} is a comma-separated list of
    layer names. The names are arbitrary, and |\pgfdeclarelayer| will be called
    for every encountered argument.\footnote{To be more precise: \texttt{set
    layers} calls \texttt{\textbackslash pgfdeclarelayer} when it uses
    \meta{ordered layer names}.} There is just one ``magic'' name: the layer
    |main| should be part of every \meta{ordered layer names} as it will
    contain every graphical element which is not associated with a specific
    layer.

    The second argument \meta{style definitions} contains options -- just as if
    you would have written \meta{key}|/.style=|\marg{style definitions}. The
    \meta{style definitions} are supposed to contain \PGFPlots{} style
    redefinitions which make use of each encountered element of \meta{ordered
    layer names}. This is probably best explained by an example: the
    |layers/standard| layer configuration is defined by
    %
\begin{codeexample}[code only]
\pgfplotsset{
    layers/standard/.define layer set={
        axis background,axis grid,axis ticks,axis lines,axis tick labels,
        pre main,main,axis descriptions,axis foreground
    }{
        grid style=         {/pgfplots/on layer=axis grid},
        tick style=         {/pgfplots/on layer=axis ticks},
        axis line style=    {/pgfplots/on layer=axis lines},
        label style=        {/pgfplots/on layer=axis descriptions},
        legend style=       {/pgfplots/on layer=axis descriptions},
        title style=        {/pgfplots/on layer=axis descriptions},
        colorbar style=     {/pgfplots/on layer=axis descriptions},
        ticklabel style=    {/pgfplots/on layer=axis tick labels},
        axis background@ style={/pgfplots/on layer=axis background},
        3d box foreground style={/pgfplots/on layer=axis foreground},
    },
}
\end{codeexample}
    %
    \noindent This definition declares a couple of layers, and it adjusts
    \PGFPlots{} styles by adding |on layer| commands. The arguments for
    |on layer| are the elements of \meta{ordered layer names}.

    Note that if you have an element in \meta{ordered layer names} which is
    never referenced inside of \meta{style definitions}, this layer will always
    be empty. In other words: the \emph{only} reference to the names in
    \meta{ordered layer names} is \meta{style definitions}, \PGFPlots{} has no
    hard-coded magic layer names (except for |main| as explained above).

    Since the second argument \meta{style definitions} defines \meta{key} to be
    a normal style key, one can simply use \meta{key} in order to set
    \meta{style definitions}. This allows to inherit them. For example, the
    |layers/axis on top| layer configuration is defined by means of
    %
\begin{codeexample}[code only]
\pgfplotsset{
    /pgfplots/layers/axis on top/.define layer set={
        axis background,pre main,main,axis grid,axis ticks,axis lines,
        axis tick labels,axis descriptions,axis foreground
    }{/pgfplots/layers/standard},
}
\end{codeexample}
    %
    \noindent i.e.\@ it only redefines the \emph{sequence} of the layers and
    reuses the style definitions of |layers/standard|.

    Any number of layer configurations can be defined.
\end{handler}


\subsection{Changing the Layer of Graphical Elements}

There are a couple of keys which change the layer of a graphical element.

\begin{pgfplotskey}{on layer=\marg{layer name}}
    Providing this key somewhere in a \PGFPlots{} style or inside of a
    \PGFPlots{} axis will change the layer for all graphical elements for which
    the style applies.

    For example,
    %
\begin{codeexample}[code only]
...
\begin{axis}[set layers,grid style={/pgfplots/on layer=axis foreground}]
...
\end{codeexample}
    %
    \noindent will change the layer for any grid lines to |axis foreground|.

    The argument \meta{layer name} is expected to be part of the current layer
    configuration, i.e.\@ the argument of |set layers| should contain it.

    Note that if you have two \emph{plots} with different values of |on layer|,
    you may also want to enable |clip mode=clip individual| or to deactivate
    clipping altogether using |clip=false|. Clipping options need to be
    provided as option to the axis, not to the plot. The technical background
    is that clip paths needs to be replicated for the layer on which the
    drawing is supposed to happen -- otherwise they will be applied to the
    wrong layer.
\end{pgfplotskey}

\begin{pgfplotskey}{mark layer=\mchoice{auto,like plot,\meta{layer name}} (initially auto)}
    An advanced key which defines the layer for plot |mark|s. It is typically
    the best choice to leave it at |auto|.

    If you write |\addplot[on layer=|\meta{layer name}|]|, the layer will be
    used for the complete plot. Plot marks are treated with special care, so
    you can define an own layer for plot marks.

    The initial choice \declaretext{auto} will automatically define a
    ``suitable'' choice, leaving the responsibility with \PGFPlots{}. Here,
    ``suitable'' means to respect |clip mode| and |clip marker paths| in a way
    such that plot marks will not be clipped even though the default layer for
    your plot will be clipped.

    The choice \declaretext{like plot} will pack the marks onto the same layer
    as the plot they belong to. This might cause clipped markers, i.e.\@
    markers which are only displayed partially if they are close to the
    boundary of the axis.

    Finally, one can provide any \meta{layer name}, just as for |on layer| --
    but the layer can be different from the layer used for the plot.
\end{pgfplotskey}

}
